package com.anjubao.parking.municipal.roadside.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.anjubao.parking.municipal.basezone.dto.Base64Dto;
import com.anjubao.parking.municipal.basezone.dto.FileUploadResDTO;
import com.anjubao.parking.municipal.common.dto.ApiResult;
import com.anjubao.parking.municipal.common.global.BusinessCodeEnum;
import com.anjubao.parking.municipal.common.utils.BeanUtils;
import com.anjubao.parking.municipal.common.utils.MunicipalParkingUtils;
import com.anjubao.parking.municipal.common.utils.RedisClientTemplate;
import com.anjubao.parking.municipal.common.utils.U;
import com.anjubao.parking.municipal.parkinglot.dto.*;
import com.anjubao.parking.municipal.roadside.constant.*;
import com.anjubao.parking.municipal.roadside.dto.DefaultResponseDto;
import com.anjubao.parking.municipal.roadside.dto.DeviceRegisterResultDto;
import com.anjubao.parking.municipal.roadside.dto.cmd.*;
import com.anjubao.parking.municipal.roadside.feign.FileServiceClient;
import com.anjubao.parking.municipal.roadside.feign.ParkingLotServiceClient;
import com.anjubao.parking.municipal.roadside.feign.ParkingRecordServiceClient;
import com.anjubao.parking.municipal.roadside.feign.UserServiceClient;
import com.anjubao.parking.municipal.roadside.form.AlarmReportForm;
import com.anjubao.parking.municipal.roadside.form.HeartbeatForm;
import com.anjubao.parking.municipal.roadside.form.ImgreportForm;
import com.anjubao.parking.municipal.roadside.form.*;
import com.anjubao.parking.municipal.roadside.mapper.ParkingLotSlotMapper;
import com.anjubao.parking.municipal.roadside.mapper.ParkingRecordMapper;
import com.anjubao.parking.municipal.roadside.model.*;
import com.anjubao.parking.municipal.user.dto.UserInfoDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.ReactiveZSetCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuchunfeng
 * @date 2019/6/18 8:58
 */

@Service
@Slf4j
public class DeviceApiService {

    @Autowired
    private FileServiceClient fileServiceClient;


    @Autowired
    private ParkingRecordServiceClient parkingRecordServiceClient;

    @Autowired
    private ParkingLotServiceClient parkingLotServiceClient;

    @Autowired
    private UserServiceClient userServiceClient;


    @Autowired
    private DeviceVideoPileService deviceVideoPileService;


    @Autowired
    private ParkingRecordService parkingRecordService;


    @Resource
    private ParkingRecordMapper parkingRecordMapper;

    @Autowired
    private ParkingImageService parkingImageService;

    @Autowired
    private PayRecordService oweRecordService;


    @Autowired
    private DeviceStatusService deviceStatusService;


    @Autowired
    private ParkingLotService parkingLotService;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private ParkingLotSlotService parkingLotSlotService;

    @Autowired
    private ParkingLotSlotMapper parkingLotSlotMapper;

    @Autowired
    private DeviceLogImageService deviceLogImageService;

    @Resource
    private RedisService redisService;
    @Resource
    private DeviceOperationService deviceOperationService;

    @Autowired
    private RedisClientTemplate redisClientTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${timeOut:100}")
    private String timeOut;


    @Value("${wechatUrl:http://city-parking.dev1.dyajb.com/parkingWechat/notify/}")
    private String wechatUrl;

    /**
     * 心跳处理
     * @param heartbeatForm 心跳上报参数
     * @return 心跳回复
     */
    public Object handleHeartbeat(HeartbeatForm heartbeatForm) {

        /*检查设备时间,如果设备时间服务器时间相差超过10秒,手动对时*/
        this.checkDeviceTime(heartbeatForm);

        String devid = heartbeatForm.getDevid();
        String id = heartbeatForm.getId();
        Map<String, String> param = redisService.getCmd(devid);
        String cmd = param.get("cmd");

        //更新redis设备最后更新时间 device_last_update_time
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(heartbeatForm.getSecond());
        Date time = new Date(lt*1000);
        String sec=formatter.format(time);

        // @return Boolean
        Boolean flat=this.redisClientTemplate.getOpsForZSet().add("device_last_update_time",heartbeatForm.getDevid(), Double.parseDouble(heartbeatForm.getSecond())*1000);
        //true 就是插入，false为更新,更新不需要更新数据库状态,插入更新
        if(flat==true){
            DeviceStatus deviceStatus=deviceStatusService.getById(devid);
            deviceStatus.setIsOnline(DeviceStatusEnum.Normal.getCode());
            deviceStatusService.updateById(deviceStatus);
        }

        //没有需要下发的命令
        if (StringUtils.isEmpty(cmd)) {
            return new DefaultResponseDto();
        }
        //手动对时
        if (CommandConstants.MANUALSYNCTIME.equals(cmd)) {
            ManualsynctimeCmdDto manualsynctimeCmdDto = new ManualsynctimeCmdDto();
            manualsynctimeCmdDto.setCmd(CommandConstants.MANUALSYNCTIME);
            manualsynctimeCmdDto.setDevid(devid);
            manualsynctimeCmdDto.setId(id);
            manualsynctimeCmdDto.setSecond(System.currentTimeMillis()/1000);
            log.info("手动对时指令下发 ---------------- "+ U.json(manualsynctimeCmdDto));
            return manualsynctimeCmdDto;
        }

        //手动抓拍 attention: 手动抓拍结果在报警接口返回
        if(CommandConstants.MANUALSNAPCTRL.equals(cmd)){
            ManualsnapctrlCmdDto manualsnapctrlCmdDto = new ManualsnapctrlCmdDto();
            manualsnapctrlCmdDto.setCmd(cmd);
            manualsnapctrlCmdDto.setDevid(devid);
            manualsnapctrlCmdDto.setId(id);
            manualsnapctrlCmdDto.setChannel(0);
            log.info("手动抓拍指令下发 ---------------- "+U.json(manualsnapctrlCmdDto));
            return manualsnapctrlCmdDto;
        }
        //10.3 地锁、停车指示灯控制
        //10.3.1 下发命令格式
        //todo : 登录回复
        if(CommandConstants.MCUCTRL.equals(cmd)){
            McuctrlCmdDto mcuctrlCmdDto = new McuctrlCmdDto();
            mcuctrlCmdDto.setLock(Integer.valueOf(param.get("lock")));
            mcuctrlCmdDto.setLed(param.get("led"));
            mcuctrlCmdDto.setId(id);
            mcuctrlCmdDto.setCmd(cmd);
            mcuctrlCmdDto.setDevid(devid);
            log.info(" 地锁、停车指示灯控制---------------"+U.json(mcuctrlCmdDto));
            return mcuctrlCmdDto;
        }

        //10.4 查询视频充电停车设备状态
        if (CommandConstants.DEVQUERY.equals(cmd)) {
            DevqueryCmdDto devqueryCmdDto = new DevqueryCmdDto();
            devqueryCmdDto.setCmd(cmd);
            devqueryCmdDto.setDevid(devid);
            devqueryCmdDto.setId(id);
            log.info("查询设备状态----------------"+U.json(devqueryCmdDto));
            return devqueryCmdDto;
        }
        //10.4 查询视频充电停车设备状态
        if (CommandConstants.DEVREBOOT.equals(cmd)) {
            DevrebootCmdDto devrebootCmdDto = new DevrebootCmdDto();
            devrebootCmdDto.setCmd(cmd);
            devrebootCmdDto.setDevid(devid);
            devrebootCmdDto.setId(id);
            log.info("重启设备----------------"+U.json(devrebootCmdDto));
            return devrebootCmdDto;
        }
        //二维码下发
        if (CommandConstants.RQCODE.equals(cmd)) {
            RqcodeCmdDto rqcodeCmdDto = new RqcodeCmdDto();
            rqcodeCmdDto.setCmd(cmd);
            rqcodeCmdDto.setDevid(devid);
            rqcodeCmdDto.setId(id);
            rqcodeCmdDto.setDevtype(heartbeatForm.getDevtype());
            rqcodeCmdDto.setType(param.get("type"));
            rqcodeCmdDto.setCode(param.get("code"));
            return rqcodeCmdDto;
        }
        //泊位号下发
        if (CommandConstants.BERTHNUM.equals(cmd)) {
            BerthnumCmdDto berthnumCmdDto = new BerthnumCmdDto();
            berthnumCmdDto.setSecond(System.currentTimeMillis()/1000);
            berthnumCmdDto.setDevtype(heartbeatForm.getDevtype());
            berthnumCmdDto.setDevid(devid);
            berthnumCmdDto.setCmd(cmd);
            berthnumCmdDto.setId(param.get("id"));
            return berthnumCmdDto;
        }
        log.warn("未知的命令 cmd: {} *****************",cmd);
        return new DefaultResponseDto();

    }

    /*检查设备时间,如果设备时间服务器时间相差超过10秒,手动对时*/
    private void checkDeviceTime(HeartbeatForm heartbeatForm) {
        int deviceTime = Integer.valueOf(heartbeatForm.getSecond());
        int currentTime = (int) (System.currentTimeMillis() / 1000);
        int absoluteTime = Math.abs(deviceTime - currentTime);
        if (absoluteTime > 20) {
            log.info("触发手动对时 deviceTime:{}, currentTime:{}, absoluteTime:{}",deviceTime,currentTime,absoluteTime);
            deviceOperationService.manualSyncTime(heartbeatForm.getDevid());
        }
    }

    /**
     * 停车图片上报处理
     * @param imgreportForm 停车图片上报参数
     * @return 回复
     */
    public Object handleImgreport(ImgreportForm imgreportForm) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ApiResult<UserInfoDto> userRes=userServiceClient.getUserByVehicle(imgreportForm.getLicense());
        int direction=imgreportForm.getDirection();
        String devid=imgreportForm.getDevid();
        String id=imgreportForm.getId();
        String devtype=imgreportForm.getDevtype();
        String cmd=imgreportForm.getCmd();
        //获取时间信息
        JSONArray picdatas=imgreportForm.getPicdata();
        JSONObject picdata= (JSONObject) picdatas.get(0);
        JSONObject timeStamp=picdata.getJSONObject("timeStamp");
        String sec=timeStamp.getStr("sec");
        long lt = new Long(sec);
        Date time = new Date(lt*1000);

        ImgreportCmdDto imgreportCmdDto = new ImgreportCmdDto();
        imgreportCmdDto.setDevtype(devtype);
        imgreportCmdDto.setDevid(devid);
        imgreportCmdDto.setCmd(cmd);
        imgreportCmdDto.setId(id);
        //停车状态未知，不处理业务
        if(direction== DirectionEnum.UnKnow.getCode()){
            imgreportCmdDto.setResponse("1");
            return imgreportCmdDto;
        }
        //停车停稳，不处理业务
        else if(direction==DirectionEnum.Stop.getCode()){
            imgreportCmdDto.setResponse("1");
            return imgreportCmdDto;
        }
        //停车驶入，处理业务
        else if(direction==DirectionEnum.In.getCode()){
            //入库去重,不为空即返回
            ParkingRecord repeatRecord=parkingRecordMapper.getRepeatRecord(formatter.format(time),imgreportForm.getLicense());
            if(repeatRecord!=null){
                imgreportCmdDto.setResponse("1");
                return imgreportCmdDto;
            }


            //slot parking_record_id
            //通过slot_num查找泊位
            QueryWrapper<ParkingLotSlot> queryWrapper=new QueryWrapper();
            queryWrapper.eq("slot_num",id);
            ParkingLotSlot slot=parkingLotSlotMapper.selectOne(queryWrapper);
            if(!StringUtils.isEmpty(slot.getParkingRecordId())){
                //查询存在的入库记录
                ParkingRecord oldRecord=parkingRecordMapper.selectById(slot.getParkingRecordId());
                this.parkingOut(oldRecord,ParkingOutStateEnum.abnormal.getCode(),userRes,null);
            }

            ParkingRecord record=new ParkingRecord();
            DeviceVideoPile videoPile=deviceVideoPileService.getById(MunicipalParkingUtils.getIdByCode(devid));

            ParkingLot parkingLot=parkingLotService.getById(videoPile.getParkingLotId());
            if(imgreportForm.getPicnum()>0){


                record.setId(U.id().toString())
                        .setParkingLotId(videoPile.getParkingLotId()).setParkingLotCode(videoPile.getParkingLotCode()).setVehicleNumber(imgreportForm.getLicense())
                        .setParkingLotName(videoPile.getParkingLotName()).setParkingLotAddress(parkingLot.getAddress())
                        //泊位编号即为平台配置的id
                        .setSlotNum(id).setParkingLotSlotCode(slot.getCode())
                        .setInTime(time).setFeeState(FeeStateEnum.OnGoing.getCode())
                        .setParkingType(ParkingTypeEnum.Low.getCode());
                if(userRes.getResult()!=null){
                    record.setUserId(userRes.getResult().getUserCode());
                    /*{
                        "title": "车辆进场",
                        "name": "安居宝路边停车",
                        "progress": "进场",
                        "remark": "当前时间2019-01-01"
                    }*/
                    com.alibaba.fastjson.JSONObject msg=new com.alibaba.fastjson.JSONObject();
                    msg.put("title","车辆进场");
                    msg.put("name","安居宝路边停车");
                    msg.put("progress","进场");
                    msg.put("remark","当前时间"+formatter.format(new Date()));
                    this.restTemplate.postForObject(wechatUrl+userRes.getResult().getUserCode(),msg,ApiResult.class);
                }else {
                    record.setUserId(null);
                }
                parkingRecordMapper.insert(record);
                slot.setParkingRecordId(record.getId());
                parkingLotSlotMapper.updateById(slot);



                //停车记录同步去平台
                EntryEnterDTO enterDTO=new EntryEnterDTO();
                enterDTO.setParkingLotCode(videoPile.getParkingLotCode())
                        .setSystemType(SystemTypeEnum.RoadSide.getCode())
                        .setParkingLotSlotCode(slot.getCode())
                        .setLocalRecordId(record.getId())
                        .setEnterDateTime(LocalDateTime.ofInstant(record.getInTime().toInstant(), ZoneId.systemDefault()))
                        .setParkingType(0);
                try{
                    ApiResult<EntryResDTO> entryRes = parkingRecordServiceClient.enter(enterDTO);
                    //保存图片
                    List<SnapshotsDto> snapshots =new ArrayList<>();

                    snapshots=this.picsUpload(snapshots,picdatas,record.getId(),ImageTypeEnum.In.getCode());

                    EntryShotUrlDTO shotUrlDTO=new EntryShotUrlDTO();
                    shotUrlDTO.setParkingLotCode(enterDTO.getParkingLotCode()).setParkingLotCode(enterDTO.getLocalRecordId())
                            .setParkingRecordCode(entryRes.getResult().getParkingRecordCode()).setSnapshots(snapshots);
                    parkingRecordServiceClient.snapShotUrl(shotUrlDTO);
                }catch (Exception e){
                    log.info("feign超时----------------"+e.getMessage());
                }


            }
            imgreportCmdDto.setResponse("1");
            return imgreportCmdDto;
        }
        //停车驶出，处理业务
        else if(direction==DirectionEnum.Out.getCode()){

            ParkingRecord parkingRecord=parkingRecordMapper.getNoOutRecord(imgreportForm.getLicense());
            if(parkingRecord==null){
                imgreportCmdDto.setResponse("1");
                return imgreportCmdDto;
            }
            if(imgreportForm.getPicnum()>0){

                this.parkingOut(parkingRecord,ParkingOutStateEnum.notSpecified.getCode(),userRes,picdatas);
            }
            imgreportCmdDto.setResponse("1");
            return imgreportCmdDto;
        }
        imgreportCmdDto.setResponse("1");
        return imgreportCmdDto;
    }

    private void parkingOut(ParkingRecord oldRecord,Integer parkingOutState,ApiResult<UserInfoDto> userRes,JSONArray picdatas) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        oldRecord.setOutTime(new Date());
        oldRecord.setFeeState(FeeStateEnum.ToPayCost.getCode());
        oldRecord.setState(parkingOutState);
        parkingRecordMapper.updateById(oldRecord);
        //停车记录同步去平台
        EntryLeaveDTO leaveDTO=new EntryLeaveDTO();
        ParkingLot parkingLot=parkingLotService.getById(oldRecord.getParkingLotId());

        //通过slot_num查找泊位
        QueryWrapper<ParkingLotSlot> queryWrapper=new QueryWrapper();
        queryWrapper.eq("slot_num",oldRecord.getSlotNum());
        ParkingLotSlot slot=parkingLotSlotMapper.selectOne(queryWrapper);

        leaveDTO.setParkingLotCode(parkingLot.getCode())
                .setSystemType(SystemTypeEnum.RoadSide.getCode()).setParkingLotSlotCode(slot.getCode()).setLocalRecordId(oldRecord.getId()).setEnterDateTime(LocalDateTime.ofInstant(oldRecord.getInTime().toInstant(), ZoneId.systemDefault()))
                .setLeaveTime(LocalDateTime.ofInstant(oldRecord.getOutTime().toInstant(), ZoneId.systemDefault()))
                .setParkingType(0);
        Duration duration = Duration.between(leaveDTO.getEnterDateTime(),leaveDTO.getLeaveTime());
        leaveDTO.setParkingDuration((int) (duration.toMillis()/1000));
        // 费用待完善
        ApiResult<ParkingTotalFeeDto> feeRes=parkingLotServiceClient.getParkingTotalFee(parkingLot.getCode(),leaveDTO.getEnterDateTime(),leaveDTO.getLeaveTime());
        leaveDTO.setFeeTotal(feeRes.getResult().getTotalFee()).setDiscountTotal(0);
        leaveDTO.setPaidTotal(feeRes.getResult().getTotalFee()-leaveDTO.getDiscountTotal()).setBatteryChargingDuration(0).setIsBatteryCharged(0).setParkingDetectType(1);
        try{
            //云平台记录上报
            ApiResult<EntryResDTO> leaveRes=parkingRecordServiceClient.leave(leaveDTO);

            //保存图片
            if(parkingOutState!=2){
                List<SnapshotsDto> snapshots =new ArrayList<>();
                snapshots=  this.picsUpload(snapshots,picdatas,oldRecord.getId(),ImageTypeEnum.Out.getCode());
                EntryShotUrlDTO shotUrlDTO=new EntryShotUrlDTO();
                shotUrlDTO.setParkingLotCode(leaveDTO.getParkingLotCode()).setParkingLotCode(leaveDTO.getLocalRecordId())
                        .setParkingRecordCode(leaveRes.getResult().getParkingRecordCode()).setSnapshots(snapshots);
                parkingRecordServiceClient.snapShotUrl(shotUrlDTO);
            }

        }catch (Exception e){
            log.info("feign超时----------------"+e.getMessage());
        }


        PayRecord payRecord=new PayRecord();
        Long ltime =Long.valueOf(new SimpleDateFormat("yyMMddhhmmssSSS").format(new Date()));
        //todo 判断用户是否注册
        if(userRes.getResult()!=null){
            payRecord.setUserId(userRes.getResult().getUserCode());
            payRecord.setId(String.valueOf(userRes.getResult().getUserCode()+ BusinessEnum.A.getCode()+ltime));
            com.alibaba.fastjson.JSONObject msg=new com.alibaba.fastjson.JSONObject();
            msg.put("title","车辆出场");
            msg.put("name","安居宝路边停车");
            msg.put("progress","出场");
            msg.put("remark","当前时间"+formatter.format(new Date()));
            this.restTemplate.postForObject(wechatUrl+userRes.getResult().getUserCode(),msg,ApiResult.class);
        }else {
            payRecord.setId(String.valueOf("0000000000000000"+ BusinessEnum.A.getCode()+ltime));

        }
        //生成欠缴记录
        payRecord.setRecordType(RecordTypeEnum.Low.getCode());
        payRecord.setParkingRecordId(oldRecord.getId());
        //todo 计费规则待定
        payRecord.setAmount(feeRes.getResult().getTotalFee());
        payRecord.setPayState(PayStateEnum.ToBePaid.getCode());
        payRecord.setPayType(PayTypeEnum.AfterPaying.getCode());
        oweRecordService.save(payRecord);
        //泊位停车记录置空串
        slot.setParkingRecordId("");
        parkingLotSlotMapper.updateById(slot);
    }

    public Object handleAlarmReport(AlarmReportForm alarmReportForm) {


        AlarmreportCmdDto cmdDto=new AlarmreportCmdDto();
        cmdDto.setCmd(alarmReportForm.getCmd());
        cmdDto.setDevid(alarmReportForm.getDevid());
        cmdDto.setDevtype(alarmReportForm.getDevtype());
        cmdDto.setId(alarmReportForm.getId());
        DeviceVideoPile videoPile=deviceVideoPileService.getById(MunicipalParkingUtils.getIdByCode(alarmReportForm.getDevid()));
        DeviceStatus deviceStatus=deviceStatusService.getById(MunicipalParkingUtils.getIdByCode(alarmReportForm.getDevid()));

        //通过slot_num查找泊位
        QueryWrapper<ParkingLotSlot> queryWrapper=new QueryWrapper();
        queryWrapper.eq("slot_num",alarmReportForm.getId());
        ParkingLotSlot parkingLotSlot=parkingLotSlotMapper.selectOne(queryWrapper);




        com.alibaba.fastjson.JSONObject timeStamp=alarmReportForm.getTimeStamp();
        String sec=timeStamp.getString("sec");
        long piclt = new Long(sec);
        Date picTime = new Date(piclt);

        ParkingLot parkinglot=parkingLotService.getById(videoPile.getParkingLotId());

        if(videoPile!=null){
            DeviceLog deviceLog=new DeviceLog();
            //TODO token setUsedStatus
            deviceLog.setId(U.id()).setToken("1").setUsedStatus(1)
                    .setDeviceId(Long.valueOf(MunicipalParkingUtils.getIdByCode(alarmReportForm.getDevid())))
                    .setDeviceCode(videoPile.getCode()).setDeviceType(videoPile.getType())
                    .setDeviceName(videoPile.getName())
                    .setIsOnline(deviceStatus.getIsOnline()).setStatus(deviceStatus.getStatus())
                    .setParkingLotSlotId(parkingLotSlot.getId()).setParkingLotSlotCode(parkingLotSlot.getCode())
                    .setParkingLotSlotName(parkingLotSlot.getSlotNum()).setLocation(parkinglot.getAddress())
                    .setEventId("warning_"+alarmReportForm.getAlarmtype()).setEventTime(picTime)
                    .setEventInfo(AlarmTypeEnum.getDescByCode(String.valueOf(alarmReportForm.getAlarmtype()))).setNote(AlarmTypeEnum.getNotesByCode(String.valueOf(alarmReportForm.getAlarmtype())));
            deviceLogService.save(deviceLog);
            Base64Dto base64Dto=new Base64Dto();
            base64Dto.setBase64(alarmReportForm.getImageFile());
            ApiResult<FileUploadResDTO> res=fileServiceClient.Base64(base64Dto);
            DeviceLogImage deviceLogImage=new DeviceLogImage();
            deviceLogImage.setReportUrl(res.getResult().getUrl()).setDeviceLogId(deviceLog.getId());
            deviceLogImageService.save(deviceLogImage);

        }
        cmdDto.setResponse("1");
        return cmdDto;
    }

    public Object handleLogin(DeviceRegisterForm deviceRegisterForm) {
        DeviceRegisterResultDto dto= BeanUtils.transform(DeviceRegisterResultDto.class, deviceRegisterForm);
        //redis device_status:{devid}
        Integer status=redisClientTemplate.getInt("device_status:"+deviceRegisterForm.getDevid());
        if(status!=null){
            if(status!=DeviceStatusEnum.Normal.getCode()){
                dto.setRespsonse("0").setReason("设备状态不可用");
                return  dto;
            }
        }else{
            //redis为空时，记录添加进去redis
            DeviceStatus deviceStatus=deviceStatusService.getById(MunicipalParkingUtils.getIdByCode(deviceRegisterForm.getDevid()));

            redisClientTemplate.set("device_status:"+deviceRegisterForm.getDevid(),deviceStatus.getStatus());
            redisClientTemplate.expire("device_status:"+deviceRegisterForm.getDevid(), Long.parseLong(timeOut), TimeUnit.SECONDS);
            if(deviceStatus.getStatus()!=DeviceStatusEnum.Normal.getCode()){
                dto.setRespsonse("0").setReason("设备状态不可用");
                return  dto;
            }

            deviceStatusService.updateDeviceStatus(String.valueOf(MunicipalParkingUtils.getIdByCode(deviceRegisterForm.getDevid())));
            // device_is_online:{devid}
            redisClientTemplate.set("device_is_online:"+deviceRegisterForm.getDevid(),DeviceIsOnlineEnum.OnLine.getCode());
            redisClientTemplate.expire("device_is_online:"+deviceRegisterForm.getDevid(), Long.parseLong(timeOut), TimeUnit.SECONDS);
        }
        dto.setRespsonse("1");
        return dto;
    }


    public List<SnapshotsDto> picsUpload( List<SnapshotsDto> snapshots,JSONArray picDatas,String parkingRecordId,Integer imageType){
        JSONObject picItem= (JSONObject) picDatas.get(0);
        JSONObject timeStamp=picItem.getJSONObject("timeStamp");
        String sec=timeStamp.getStr("sec");

        for(int i=0;i<picDatas.size();i++){
            JSONObject pic= (JSONObject) picDatas.get(i);
            Date picTime = new Date(new Long(sec)*1000);
            String imageFile=pic.getStr("imageFile");
            Base64Dto base64Dto=new Base64Dto();
            base64Dto.setBase64(imageFile);
            ApiResult<FileUploadResDTO> res=fileServiceClient.Base64(base64Dto);
            ParkingImage parkingImage=new ParkingImage();
            parkingImage.setParkingRecordId(Long.valueOf(parkingRecordId)).setImageType(imageType)
                    .setCaptureImage(res.getResult().getUrl()).setCaptureTime(picTime);
            parkingImageService.save(parkingImage);
            SnapshotsDto snapshotsDto=new SnapshotsDto();
            snapshotsDto.setSnapshotUrl(res.getResult().getUrl()).setType(2);
            snapshots.add(snapshotsDto);
        }

        return snapshots;
    }
}
